<template>
  <div class="yy-knowledgebase-maintenance">
    <!--列表-->
    <div class="yy-supplier-manage-list" v-show="type=='list'">
      <Card>
        <p slot="title">
          <Icon type="md-list" />
          知识库维护列表
        </p>
        <Form ref="formInline" :model="formSearch"  inline>
            <FormItem prop="user">
              <Input type="text" v-model="formSearch.knowleTitle" placeholder="知识标题"></Input>
            </FormItem>
            <FormItem prop="user">
              <Select class="select" v-model="formSearch.dsNum" placeholder="分类">
                <Option value="">请选择</Option>
                <Option v-for="(item,index) in knowledgeClassification" :value="item.dsNum" :key="index">
                  {{item.dsName}}
                </Option>
              </Select>
            </FormItem>
            <FormItem>
              <Button type="primary" @click="handleSearch()">查询</Button>
            </FormItem>
            <FormItem>
              <Button type="primary" @click="handleAdd()">新增</Button>
            </FormItem>
        </Form>
        <Table :columns="columns" :data="data" ></Table>
        <div style="margin: 10px;overflow: hidden">
          <div style="float: right;">
              <Page :total="page.total" :page-size="page.pageSize" :current="1" @on-change="changePage" show-total></Page>
          </div>
        </div>
      </Card>
    </div>
    <!--详情-->
    <div class="yy-supplier-manage-details" v-show="type=='details'">
       <Card>
        <p slot="title">
          <Icon type="md-paper"/>
          查看详情
        </p>
        <p slot="extra">
          <Button type="primary" @click="goBack()">返回</Button>
        </p>
        <div class="details">
          <p class="details-title"><span>知识标题:</span>{{currentData.f_KnowleTitle}}</p>
          <p class="details-title"><span>摘要:</span>{{currentData.f_KnowleDigest}}</p>
          <p class="details-title"><span>关键词:</span>{{currentData.f_KnowleKeyword}}</p>
          <p class="details-title"><span>分类:</span>{{currentData.dsName}}</p>
          <p class="details-title"><span>知识内容:</span></p>  
          <Card  class="contract-upload-list-content">{{currentData.f_KnowleContent}}</Card>
          <p class="details-title"><span>附件:</span>
            <div class="contract-upload-list" v-for="item in uploadList" :key="item.url">
              <div class="contract-upload-list-text">
                {{item.f_FileExtension}}
              </div>
              <div class="contract-upload-list-cover">
                <Icon type="ios-cloud-download-outline" @click.native="handleView(item)"></Icon>
              </div>
            </div>
          </p>
        </div>
      </Card>
    </div>
    <!--添加/编辑-->
    <div class="yy-supplier-manage-add-edit"  v-show="(type=='add' || type=='edit')">
      <Card>
        <p slot="title">
          <template v-if="type=='add'"> 
            <Icon type="md-create"/> 新增
          </template>
          <template v-if="type=='edit'"> 
            <Icon type="md-document"/>编辑
          </template>
        </p>
        <p slot="extra" >
          <Button type="primary" @click="goBack()">返回</Button>
        </p>
        <div class="editForm">
          <Form ref="editForm" :model="editFormInLine" :rules="editFormRuleInline" :label-width="100" @keydown.native.enter.prevent ="handleSubmit">
             <FormItem label="知识标题" prop="f_KnowleTitle">
              <Input v-model="editFormInLine.f_KnowleTitle" placeholder="请输入知识标题"></Input>
            </FormItem>
            <FormItem label="摘要"  prop="f_KnowleDigest">
              <Input v-model="editFormInLine.f_KnowleDigest" placeholder="请输入摘要"></Input>
            </FormItem>
            <FormItem label="关键词"  prop="f_KnowleKeyword">
              <Input v-model="editFormInLine.f_KnowleKeyword" placeholder="关键字"></Input>
            </FormItem>
            <FormItem label="分类"  prop="dsNum">
              <Select class="select" v-model="editFormInLine.dsNum" placeholder="分类">
                <Option value="">请选择</Option>
                <Option v-for="(item,index) in knowledgeClassification" :value="item.dsNum" :key="index">
                  {{item.dsName}}
                </Option>
              </Select>
            </FormItem> 
            <FormItem label="知识内容" prop="f_KnowleContent" style="width:600px;height:250px;">
              <Input v-model="editFormInLine.f_KnowleContent" type="textarea" :autosize="{minRows: 8,maxRows: 10}" placeholder="知识内容" maxlength="1000"></Input>
            </FormItem>
            <FormItem label="上传合同">
                <div class="contract-upload-list" v-for="item in uploadList" :key="item.f_FileAllPath">
                  <div class="contract-upload-list-text">文件</div>
                  <div class="contract-upload-list-cover">
                      <Icon type="ios-trash-outline" @click.native="handleRemove(item)"></Icon>
                  </div>
                </div>
                <Upload
                  ref="upload"
                  :show-upload-list="false"
                  :on-success="handleSuccess"
                  :format="['pdf','docx','xlsx','jpg','jpeg','png']"
                  :max-size="10240"
                  :on-error="handleError"
                  :on-format-error="handleFormatError"
                  :on-exceeded-size="handleMaxSize"
                  :before-upload="handleBeforeUpload"
                  multiple
                  type="drag"
                  action="/api/UploadImg2"
                  style="display: inline-block;width:58px;">
                  <div style="width: 58px;height:58px;line-height: 58px;">
                      <Icon type="ios-camera" size="20"></Icon>
                  </div>
                </Upload>
              </FormItem>
            <FormItem>
              <Button @click="handleSubmit" type="primary" class="button">提交</Button>
              <Button @click="handleReset" type="primary" class="button">重置</Button>
            </FormItem>
          </Form>
        </div>
      </Card>
    </div>
  </div>
</template>

<script>
import API from "./api";
import ValidatorRule from "@/filters/validator-rule";
import { formatArrObjIndex, formatNetTime } from "@/libs/tools";
import i18n from "./locale";

export default {
  name: "yy-knowledgebase-maintenance",
  data() {
    return {
      i18n: i18n,
      currentData: "",
      detailsModal: false,
      imgUrl: "",
      visible: false,
      uploadList: [],
      type: "list",
      page: {
        total: 0,
        pageSize: 20
      },
      formSearch: {
        knowleTitle: "",
        dsNum: ""
      },
      editFormInLine: {
        pK_KnowledgeID: "",
        f_KnowleTitle: "",
        f_KnowleDigest: "",
        f_KnowleKeyword: "",
        f_KnowleContent: "",
        f_KnowleCreateDT: "",
        knowLedgeFiles: [],
        userID: "",
        dsNum: "",
        dsName: ""
      },
      editFormRuleInline: {
        f_KnowleTitle: ValidatorRule.require
        //dsNum: ValidatorRule.select,
      },
      columns: [
        {
          title: "知识标题",
          key: "f_KnowleTitle"
        },
        {
          title: "分类",
          key: "dsName"
        },
        {
          title: "摘要 ",
          key: "f_KnowleDigest"
        },
        {
          title: "关键词",
          key: "f_KnowleKeyword"
        },
        {
          title: "附件个数 ",
          key: "knowLedgeFiles",
          render: (h, params) => {
            return h("span", params.row.knowLedgeFiles.length);
          }
        },
        {
          title: "录入时间 ",
          key: "f_KnowleCreateDT"
        },
        {
          title: "操作",
          key: "action",
          width: 180,
          align: "center",
          render: (h, params) => {
            return h("div", [
              h(
                "Button",
                {
                  props: {
                    type: "primary",
                    size: "small"
                  },
                  style: {
                    marginRight: "5px"
                  },
                  on: {
                    click: () => {
                      this.details(params.index);
                    }
                  }
                },
                "查看"
              ),
              h(
                "Button",
                {
                  props: {
                    type: "primary",
                    size: "small"
                  },
                  style: {
                    marginRight: "5px"
                  },
                  on: {
                    click: () => {
                      this.edit(params.index);
                    }
                  }
                },
                "编辑"
              ),
              h(
                "Button",
                {
                  props: {
                    type: "error",
                    size: "small"
                  },
                  on: {
                    click: () => {
                      this.delete(params.index, params.row.pK_KnowledgeID);
                    }
                  }
                },
                "删除"
              )
            ]);
          }
        }
      ],
      data: [],
      knowledgeClassification: []
    };
  },

  mounted() {
    this.userInfo = this.$store.state.user.userInfo;
    this.handleSearch();
    this.initClassification();
  },

  computed: {},

  methods: {
    initClassification() {
      let obj = {
        userID: "",
        userName: "",
        b_UserRole: ""
      };
      this.getClassification(obj);
    },

    getClassification(obj) {
      API.getClassification(obj)
        .then(res => {
          if (res.code == 200) {
            let data = res.data;
            this.knowledgeClassification = data.list;
          }
        })
        .catch(err => {
          this.$Message.error("请求异常！");
        });
    },

    handleSearch() {
      let obj = this.formSearch;
      obj.pageNum = 1;
      obj.pageSize = this.page.pageSize;
      this.formSearch = obj;
      this.getList(obj);
    },

    getList(obj) {
      API.getList(obj)
        .then(res => {
          if (res.code == 200) {
            let data = res.data;
            if (data != null) {
              this.page.total = data.total;
              this.page.pageSize = data.pageSize;
              this.data = data.list;
            } else {
              this.$Message.success({ content: "暂无数据！" });
              this.data = [];
            }
          }
        })
        .catch(err => {
          this.$Message.error("请求异常！");
        });
    },

    changePage(pageNum) {
      let obj = this.formSearch,
        maxPageNum = Math.ceil(this.page.total / this.page.pageSize);
      if (obj.pageNum > maxPageNum) {
        obj.pageNum = maxPageNum;
      } else {
        obj.pageNum = pageNum;
      }
      this.formSearch = obj;
      this.getList(obj);
    },

    goBack() {
      this.type = "list";
    },

    handleAdd() {
      this.type = "add";
      this.currentData = "";
      this.uploadList = [];
      this.handleReset();
    },

    details(index) {
      this.type = "details";
      this.currentData = this.data[index];
      this.uploadList = _.clone(this.currentData.knowLedgeFiles);
    },

    edit(index) {
      this.handleReset();
      this.type = "edit";
      this.currentData = this.data[index];
      this.editFormInLine = _.clone(this.currentData);
      this.uploadList = _.clone(this.currentData.knowLedgeFiles);
      //this.assembleUploadedData();
    },

    assembleUploadedData() {
      let tthis = this,
        arr = this.currentData.urls ? JSON.parse(this.currentData.urls) : [];
      this.uploadList = [];
      _.forEach(arr, function(value) {
        let obj = {
          f_FileAllPath: value
        };
        tthis.uploadList.push(obj);
      });
    },

    delete(index, id) {
      let tthis = this;
      this.$Modal.confirm({
        title: "提示：",
        content: "你确定删除这条记录",
        onOk: function() {
          let obj = {
            pK_KnowledgeID: id,
            UserID: tthis.userInfo.userId
          };
          API.delete(obj)
            .then(res => {
              if (res.code == 200) {
                this.$Message.success({ content: "该记录已经删除成功！" });
                tthis.data.splice(index, 1);
                tthis.resetList();
              }
            })
            .catch(err => {
              console.log(err);
              this.$Message.error("请求异常！");
            });
        }
      });
    },

    resetList() {
      //求余为1，页码为最大页码，请求页需减1
      let maxPageNum = Math.ceil(this.page.total / this.page.pageSize);
      let remainderNum = this.page.total % this.page.pageSize;
      if (
        this.formSearch.pageNum == maxPageNum &&
        remainderNum == 1 &&
        this.formSearch.pageNum !== 1
      ) {
        this.formSearch.pageNum = this.formSearch.pageNum - 1;
      }
      let obj = this.formSearch;
      this.getList(obj);
    },

    handleSubmit() {
      this.editFormInLine = this.addUploadToData(this.editFormInLine);
      this.$refs.editForm.validate(valid => {
        if (valid) {
          if (this.type == "edit") {
            this.editSubmit(this.editFormInLine);
          } else {
            this.addSubmit(this.editFormInLine);
          }
        }
      });
    },

    addUploadToData(obj) {
      let arr = [];
      for (let i in this.uploadList) {
        arr.push(this.uploadList[i].url);
      }
      if (arr.length > 0) {
        obj.knowLedgeFiles = JSON.stringify(arr);
      } else {
        obj.knowLedgeFiles = "";
      }
      return obj;
    },

    handleReset() {
      this.$refs.editForm.resetFields();
    },

    editSubmit(obj) {
      obj.id = this.currentData.id;
      API.editSubmit(obj)
        .then(res => {
          if (res.code == 200) {
            this.resetList();
            this.$Message.success("修改成功！");
            this.goBack();
          }
        })
        .catch(err => {
          this.$Message.error("修改异常！");
        });
    },

    addSubmit(obj) {
      API.addSubmit(obj)
        .then(res => {
          if (res.code == 200) {
            this.handleSearch();
            this.$Message.success("添加成功！");
            this.goBack();
          }
        })
        .catch(err => {
          this.$Message.error("请求异常！");
        });
    },

    /*************************图片相关***********************/
    handleView(obj) {
      /*this.imgUrl = obj.url;
      this.visible = true;*/
      window.location.href = obj.url;
    },

    handleError(err, file) {
      console.log("handleError", err);
    },

    handleRemove(file) {
      let index = formatArrObjIndex(this.uploadList, "f_FileAllPath", file.url);
      this.uploadList.splice(index, 1);
    },

    handleSuccess(res, file) {
      //file.url = file.response.data.url;
      let obj = {
        f_FileAllPath: file.response.data.url
      };
      this.uploadList.push(obj);
      //console.log(this.uploadList)
    },

    handleFormatError(file) {
      this.$Notice.warning({
        title: "文件格式不正确",
        desc: "文件" + file.name + " 的格式不正确, 请选择正确的格式."
      });
    },

    handleMaxSize(file) {
      this.$Notice.warning({
        title: "上传文件大小限制",
        desc: "文件" + file.name + " 太大,不能超过10M."
      });
    },

    handleBeforeUpload(file) {
      const check = this.uploadList.length < 4;
      if (!check) {
        this.$Notice.warning({
          title: "最多上传4个文件."
        });
      }
      return check;
    }
  }
};
</script>
<style lang="less" >
@import "./yy-knowledgebase-maintenance.less";
</style>
